package com.viknix.threadpool.manager.client.util;

import lombok.SneakyThrows;
import org.springframework.core.env.PropertyResolver;

import java.net.InetAddress;

/**
 * @Author: Dongqi
 * @Date: 2021/10/22 16:18
 * @Version 1.0
 * @Description: 实例工具
 */
public class InstanceIdUtil {

    private static final String SEPARATOR = ":";

    public static String getDefaultInstanceId(PropertyResolver resolver) {
        String namePart = getIpApplicationName(resolver);
        String indexPart = resolver.getProperty("spring.application.instance_id", resolver.getProperty("server.port"));
        return combineParts(namePart, SEPARATOR, indexPart);
    }

    @SneakyThrows
    public static String getIpApplicationName(PropertyResolver resolver) {
        InetAddress host = InetAddress.getLocalHost();
        String hostname = host.getHostAddress();
        String appName = resolver.getProperty("spring.application.name");
        return combineParts(hostname, SEPARATOR, appName);
    }

    public static String combineParts(String firstPart, String separator,
                                      String secondPart) {
        String combined = null;
        if (firstPart != null && secondPart != null) {
            combined = firstPart + separator + secondPart;
        } else if (firstPart != null) {
            combined = firstPart;
        } else if (secondPart != null) {
            combined = secondPart;
        }
        return combined;
    }

}
